//
//  MoyaConfig.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import Moya
import HandyJSON
import RxSwift

// TODO: - ⚠️：注意环境
var server = Server(isProduct: getEnvironment())

struct Server {
    
    var isProduct: Bool
    
    var APIHost: String {
        get {
            if isProduct {
                return "https://fastadmin.matenovel.com/api"
            }else {
                return "https://fastadmin.matenovel.com/api"
            }
        }
    }
    
    var H5Host: String {
        get {
            if isProduct {
                return "https://fastadmin.matenovel.com"
            }else {
                return "https://fastadmin.matenovel.com"
            }
        }
    }
}

// MARK: - 加密相关
/// 请求参数按key排序再MD5加密
func sortedMD5String(_ parameters: [String: Any]) -> String {
    var common = ""
    var neParameters = [String: Any]()
    for key in parameters.keys {
        if !isBlank(parameters[key]) {
            neParameters[key] = parameters[key]
        }
    }
    for key in (neParameters.keys.sorted(by: { $0 < $1})) {
        var value = ""
        if parameters[key] is Int {
            value = "\(neParameters[key] ?? 1)"
        }else if parameters[key] is Double {
            value = "\(neParameters[key] ?? 0.0)"
        }else {
            value = neParameters[key] as! String
        }
        common += (key + "=" + value + "&")
    }
    common.removeLast()
    common = (common+"加盐").MD5String()
    return common
}

/// URLEncoder.encode
func urlencode(_ mstring: String) -> String {
    var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
    allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
    return mstring.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? mstring
}

// MARK: - plugins
func JSONResponseDataFormatter(_ data: Data) -> Data {
    do {
        let dataAsJSON = try JSONSerialization.jsonObject(with: data)
        let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
        return prettyData
    } catch {
        return data // fallback to original data if it can't be serialized.
    }
}

extension ObservableType where Element == Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(response.mapModel(T.self))
        }
    }
}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> T {
        if data.count < 1 {
            if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "{}"){
                return emptyValue
            }else if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "[{}]"){
                return emptyValue
            }
        }
        // 获取请求response的data转成json
        let jsonString = String.init(data: data, encoding: .utf8)
        WNLog("\n====请求接口====\n\(response?.url?.path ?? "")\n====请求结果====\n\(jsonString ?? "")")
        if let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
            return model
        }
        return JSONDeserializer<T>.deserializeFrom(json: "{\"status\":\"request error\"}")!
    }
}
